package com.wframe.project.jnd.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wframe.project.jnd.rest.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.wframe.project.jnd.services.PurchaseTempService;
import com.wframe.project.jnd.util.WebUtils;
import com.wframe.project.jnd.vo.PriceBeanVo;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 采购模板
 *
 * @author lenovo
 */
@Controller
@RequestMapping("/purchasetemp")
public class PurchaseTempController {

    @Autowired
    PurchaseTempService tempService;

    @RequestMapping(value = "list")
    public String list(String psize, String pno, HttpServletRequest request, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        int pagesize = 10;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) pagesize = Integer.parseInt(psize);
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        PageResult pr = tempService.queryList(WebSession.getWbUser(request.getSession()).getUserid(), pagesize, pageno);
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        return "/website/user/purchaseTemps";
    }

    @RequestMapping(value = "edit")
    public String edit(String id, HttpServletRequest request, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        if (StringUtils.isNotBlank(id)) {
            JdataBean bean = tempService.getBuyplan(WebSession.getWbUser(request.getSession()).getUserid(), id);
            model.addAttribute("bean", bean.getDataMap());
        }
        return "/website/user/purchaseTemp_edit";
    }

    @RequestMapping(value = "show")
    public String show(String id, String like, String psize, String pno, HttpSession session, Model model) throws Exception {
        SessionUser sessionUser = WebSession.getWbUser(session);
        if (sessionUser == null) {
            return "redirect:/user/showlogin";
        }
        String userid = sessionUser.getUserid();
        int pagesize = 10;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) pagesize = Integer.parseInt(psize);
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        PageResult pr = tempService.queryPlanProduct(id, like, pagesize, pageno);
        if (WebSession.checkWbUserAuth(userid)) {
            pr = tempService.findTemplateProducts(userid, id, pagesize, pageno);
        }
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        JdataBean bean = tempService.getBuyplan(userid, id);
        model.addAttribute("bean", bean.getDataMap());
        return "/website/user/purchaseTemp_show";
    }

    @RequestMapping(value = "save")
    public void save(String id, String name, String photo, String explanation, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean bean = new JdataBean();
            bean.put("id", id);
            bean.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
            bean.put("name", name);
            bean.put("photo", photo);
            bean.put("explanation", explanation);
            String retid = tempService.saveBuyplan(bean);
            json.putData(retid);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "del")
    public void save(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            if (WebSession.getWbUser(request.getSession()) == null) {
                throw new ClientException(CodeEnum.NoAuth);
            }
            tempService.delBuyplan(WebSession.getWbUser(request.getSession()).getUserid(), id);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "remindshow")
    public String remindshow(String panid, HttpServletRequest request, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        JdataBean bean = tempService.getBuyplan(WebSession.getWbUser(request.getSession()).getUserid(), panid);
        model.addAttribute("bean", bean.getDataMap());
        return "/website/user/purchaseTemps_remindshow";
    }

    @RequestMapping(value = "remindsave")
    public void remindsave(String isremind, String panid, String remindcon, String isphone, String remindphone, String reminddata, String remindrepeat, String repeatday, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean bean = new JdataBean();
            bean.put("id", panid);
            bean.put("isremind", isremind);
            bean.put("remindcon", remindcon);
            bean.put("remindphone", remindphone);
            bean.put("reminddata", reminddata);
            bean.put("remindrepeat", remindrepeat);
            bean.put("repeatday", repeatday);
            bean.put("isphone", isphone);
            tempService.saveBuyplan(bean);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "reminddel")
    public void reminddel(String panid, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            tempService.delRemin(panid);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "addProductShow")
    public String addProductShow(String panid, String like, String pno, HttpSession session, Model model) throws Exception {
        SessionUser sessionUser = WebSession.getWbUser(session);
        if (sessionUser == null) {
            return "redirect:/user/showlogin";
        }
        String userid = sessionUser.getUserid();
        int pagesize = 20;
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        PageResult pr = tempService.queryWebProduct(like, pagesize, pageno);
        if (WebSession.checkWbUserAuth(userid)) {
            pr = tempService.findWebProducts(userid, like, pagesize, pageno);
        }
        List<Map> list = pr.getList();
        for(Map map : list){
            map.put("isOwned",tempService.checkOwned(panid,map.get("productid")));
        }
        model.addAttribute("list", list);
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        JdataBean bean = tempService.getBuyplan(userid, panid);
        model.addAttribute("bean", bean.getDataMap());
        model.addAttribute("like", like);
        return "/website/user/purchaseTemps_selproduct";
    }

    @RequestMapping(value = "addproduct")
    public void addproduct(String panid, String data, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JSONArray arrs = JSON.parseArray(data);
            if (arrs.size() == 0) throw new ClientException("请选择商品");
            List<PriceBeanVo> prices = new ArrayList<PriceBeanVo>();
            for (int i = 0; i < arrs.size(); i++)
                prices.add(new PriceBeanVo(arrs.getJSONObject(i).getString("priceid"), arrs.getJSONObject(i).getIntValue("num")));
            tempService.addBuyplanProduct(WebSession.getWbUser(request.getSession()).getUserid(), panid, prices);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "delproduct")
    public void delproduct(String panid, String priceid, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            tempService.delBuyplanProduct(WebSession.getWbUser(request.getSession()).getUserid(), panid, priceid);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "updateProduct", method = RequestMethod.POST)
    @ResponseBody
    public String updateProduct(PriceBeanVo data) {
        JsonReturn json = new JsonReturn();
        tempService.updateBuyplanProduct(data);
        return json.toString();
    }

}
